package com.example.jetpacktest.adapter

import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.ContextMenu
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.jetpacktest.R
import com.example.jetpacktest.domain.My1User

class DiffUtilTest002Adapter(var datas: List<My1User>, val context: Context): RecyclerView.Adapter<DiffUtilTest002Adapter.MyViewHolder>() {


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        return MyViewHolder(LayoutInflater.from(context).inflate(R.layout.item_diff_util_test002, parent, false))
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        val user = datas[position]
        holder.textName.text = user.name
        holder.textAge.text = "${user.age}"
    }

    override fun getItemCount(): Int {
        return datas.size
    }

    /**
     * 局部刷新，这个onBindViewHolder()有3个参数
     * payloads由DiffUtil.Callback的getChangePayload()方法提供
     */
    override fun onBindViewHolder(holder: MyViewHolder, position: Int, payloads: MutableList<Any>) {
        if(payloads.isEmpty()){
            onBindViewHolder(holder, position) //整个item都刷新
            return
        }
        val user = datas[position]
        val bundle: Bundle = payloads[0] as Bundle
        if(bundle.isEmpty){
            onBindViewHolder(holder, position) //整个item都刷新
        }else{ //局部刷新(只刷新item中的部分子view)
            Log.d(TAG, "onBindViewHolder(holder: MyViewHolder, position: Int, payloads: MutableList<Any>)局部刷新")
            val keys: Set<String> = bundle.keySet()
            for(key in keys){
                when(key){
                    KEY_NAME -> {
                        Log.d(TAG, "刷新name， user.name = ${user.name}....bundle.name = ${bundle.getString(key)}")
                        holder.textName.text = user.name
                    }
                    KEY_AGE -> {
                        Log.d(TAG, "刷新age， user.age = ${user.age}....bundle.age = ${bundle.getString(key)}")
                        holder.textAge.text = "${user.age}"
                    }
                }
            }
        }

    }


    class MyViewHolder(itemView: View): RecyclerView.ViewHolder(itemView){
        val textName: TextView = itemView.findViewById<TextView>(R.id.text_name)
        val textAge: TextView = itemView.findViewById<TextView>(R.id.text_age)
    }

    companion object{
        val TAG: String = DiffUtilTest002Adapter::class.java.simpleName
        const val KEY_NAME: String = "KEY_NAME"
        const val KEY_AGE: String = "KEY_AGE"
    }


}